Binary Tree Inorder Traversal

Given a binary tree, return the inorder traversal of its nodes’ values.

For example:

Given binary tree [1,null,2,3],

  1. 1
  2. \
  3. 2
  4. /
  5. 3

return [1,3,2].

Note: Recursive solution is trivial, could you do it iteratively?

Solution:

  1. /**
  2. * Definition for a binary tree node.
  3. * public class TreeNode {
  4. * int val;
  5. * TreeNode left;
  6. * TreeNode right;
  7. * TreeNode(int x) { val = x; }
  8. * }
  9. */
  10. public class Solution {
  11. public List<Integer> inorderTraversal(TreeNode root) {
  12. List<Integer> list = new ArrayList<>();
  13. TreeNode curr = root;
  14. Stack<TreeNode> stack = new Stack<>();
  15. while (!stack.isEmpty() || curr != null) {
  16. if (curr != null) {
  17. stack.push(curr);
  18. curr = curr.left;
  19. } else {
  20. curr = stack.pop();
  21. list.add(curr.val);
  22. curr = curr.right;
  23. }
  24. }
  25. return list;
  26. }
  27. }